package com.zzh.netty.nettyChat;/**
 * @ClassName CatClient
 * @date 2021/2/1 22:28
 * @Version 1.0
 * @Description //TODO
 */

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 *@ClassName CatClient
 *@date 2021/2/1 22:28
 *@Version 1.0
 *@Description //
 */
public class CatClient {
    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("decoder",new StringDecoder());
                            pipeline.addLast("encoder",new StringEncoder());
                            pipeline.addLast(new CatClientHandler());
                        }
                    });
            ChannelFuture cf = bootstrap.connect("119.3.126.57",8088).sync();
            System.out.println("客户端启动了~"+cf.channel().remoteAddress());
            //得到channel
            Channel channel = cf.channel();
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                channel.writeAndFlush(msg);
            }
            cf.channel().closeFuture().sync();
        }catch (Exception e) {
            System.out.println(e.toString());
        } finally {

            group.shutdownGracefully();
        }
    }
}
